import React, { useState, useEffect } from 'react'
import MessageItem from './MessageItem'
import './MessageList.css'
import PubSub from 'pubsub-js'
import { getMessageListApi } from '../../api/chat'
import { useSelector } from 'react-redux'
import WsMessageType from '@utils/Common'
import InfiniteScroll from 'react-infinite-scroll-component'
import { Spin } from '@arco-design/web-react'

function MessageList(props) {
  const [msgList, setMsgList] = useState([])
  const [hasMore, setHasMore] = useState(true)

  const userStore = useSelector((state) => state.user)
  const { id: currentUser } = userStore.info
  const { id, type } = props
  const [scrollEnd, setScrollEnd] = React.useState(true)
  const scrollRef = React.useRef()

  // 滚动处理
  let scrollTop = 0
  let scrollEndTop = 0
  let timeout = null
  const onScrollHandle = (e) => {
    if (scrollEnd !== false) {
      setScrollEnd(() => false)
    }
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      scrollEndTop = scrollRef.current?.scrollTop || 0
      if (scrollTop === scrollEndTop) {
        // 一定要停止
        setScrollEnd(() => true)
      }
    }, 300)
    scrollTop = scrollRef.current.scrollTop
  }

  useEffect(() => {
    // 订阅接收消息
    var token = PubSub.subscribe(WsMessageType.receiveMessage, (message, data) => {
      const { id, type, content, time, avatar, sender, receiver } = data
      const newMessage = {
        id,
        type,
        content,
        time,
        avatar,
        sender,
        receiver,
      }

      if (newMessage.type === '0') {
        // 单聊
        // 我发送的和我收到的
        if ((sender === currentUser && receiver === props.id) || (sender === props.id && receiver === currentUser)) {
          setMsgList((pre) => [newMessage, ...pre])
          scrollToBottom()
        }
      } else if (newMessage.type === '1') {
        // 群聊
        if (sender === currentUser || receiver === props.id) {
          setMsgList((pre) => [newMessage, ...pre])
          scrollToBottom()
        }
      }
    })
    return () => {
      PubSub.unsubscribe(token)
    }
  }, [currentUser, props])

  useEffect(() => {
    return () => {
      clearTimeout(timeout)
    }
  }, [timeout])

  useEffect(() => {
    getMessageListApi({
      messageType: type,
      sender: currentUser,
      receiver: id,
      limit: 20,
    }).then((res) => {
      const result = res?.data?.list || []
      if (result.length === 0) {
        setHasMore(false)
      } else {
        setHasMore(true)
      }
      setMsgList(result)
      scrollToBottom()
    })
  }, [currentUser, id, type])

  // 滚动到底部
  const scrollToBottom = () => {
    scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    setScrollEnd(() => true)
  }

  // 获取更多聊天记录数据，10条
  const fetchMoreData = async () => {
    let response = await getMessageListApi({
      messageType: type,
      sender: currentUser,
      receiver: id,
      limit: 20,
      messageId: msgList[msgList.length - 1].id,
    })
    const result = response?.data?.list || []
    if (result.length === 0) {
      setHasMore(false)
      return
    }
    setMsgList((pre) => [...pre, ...result])
  }

  return (
    <div
      id='scrollableDiv'
      ref={scrollRef}
      className={`messageList-scroller${scrollEnd ? '' : ' messageList-scrolling'}`}
      style={{
        // width: '100%',
        // height: '100%',
        // overflow: 'auto',
        display: 'flex',
        flexDirection: 'column-reverse',
      }}
    >
      {/*Put the scroll bar always on the bottom*/}
      <InfiniteScroll
        dataLength={msgList.length}
        next={() => fetchMoreData()}
        style={{ width: '100%', display: 'flex', flexDirection: 'column-reverse' }} //To put endMessage and loader to the top.
        inverse={true} //
        hasMore={hasMore}
        loader={<Spin dot />}
        scrollThreshold={0.85}
        scrollableTarget='scrollableDiv'
        endMessage={
          <p
            style={{
              padding: '2px 0px',
              display: 'block',
              textAlign: 'center',
              color: '#999999',
            }}
          >
            {msgList.length === 0 ? '现在开始聊天吧~' : '没有更多消息啦~'}
          </p>
        }
        onScroll={(e) => onScrollHandle(e)}
      >
        {msgList.map((msg) => (
          <div key={msg.id}>
            <MessageItem key={msg.id} msg={msg} reverse={currentUser === msg.sender} />
          </div>
        ))}
      </InfiniteScroll>
    </div>
  )
}

export default MessageList
